package no.gnet.edvd.web.controller;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import no.gnet.edvd.DataStore;
import no.gnet.edvd.web.cache.MemCache;
import no.gnet.edvd.web.types.EdvdSessionUser;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LikeController extends CommonController {

	private static Logger logger = Logger.getLogger(LikeController.class);

	@Autowired
	DataStore datastore;

	HashMap<String, Object> cache = new HashMap<String, Object>();

	@RequestMapping(value = "/api/events/like/{eventid}", method = RequestMethod.GET)
	public @ResponseBody
	String likeEvent(HttpServletRequest request,
			@PathVariable("eventid") int eventid) {
		logger.debug("Inside likeEvent, eventid=" + eventid);
		EdvdSessionUser sessionUser = sessionUser(request);
		if (sessionUser != null) {
			datastore.likeEvent(eventid,sessionUser.getPlayer());
			int likesForEvent = datastore.getLikesForEvent(eventid);
			String str = " .. ";
			if(likesForEvent>0) {
				if(likesForEvent>1){
					str = likesForEvent + " people like this";
				} else{
					str = likesForEvent + " person likes this";
				}	
			}
			MemCache.markDirty(SINGLE_EVENT_CACHE_PREFIX+eventid);
			return str;
		}
		return "nok";
	}
	
	@RequestMapping(value = "/api/events/{eventid}", method = RequestMethod.GET)
	public @ResponseBody
	String eventLikes(@PathVariable String eventid) {
		logger.debug("Inside likeEvent, eventid=" + eventid);
		return String.valueOf(datastore.getLikesForEvent(Integer.parseInt(eventid)));
	}	
	
	@RequestMapping(value = "/api/events/{eventid}/hasliked", method = RequestMethod.GET)
	public @ResponseBody
	String hasLiked(HttpServletRequest request, @PathVariable String eventid) {
		logger.debug("Inside hasLiked, eventid=" + eventid);
		EdvdSessionUser sessionUser = sessionUser(request);
		if (sessionUser != null) {		
			return String.valueOf(datastore.hasLiked(Integer.parseInt(eventid),sessionUser.getPlayer().id));
		}
		return String.valueOf(datastore.getLikesForEvent(Integer.parseInt(eventid)));
	}

}
